import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as Actions from '../Actions';
import store from '../Store';
export  default class Couter extends Component{
    constructor(props){
        super(props);
        this.onIncrement = this.onIncrement.bind(this);
        this.onDecrement = this.onDecrement.bind(this);
        this.onChange = this.onChange.bind(this);
        
        this.state =this.getOwnState();
    }
    static defaultProps ={
        level:1,
        initValue:0,
        onUpdate:f=>f
    }
    getOwnState(){
        var tmp = store.getState()[this.props.caption];
        return {
            count:tmp
        };
    }
    componentDidMount(){
        store.subscribe(this.onChange)
    }
    componentWillUnmount(){
        store.unsubscribe(this.onChange)
    }
    onChange(){
        this.setState(this.getOwnState())
    }
    onIncrement(){
        store.dispatch(Actions.increment(this.props.caption,this.props.level))
    }
    onDecrement(){
        store.dispatch(Actions.decrement(this.props.caption,this.props.level))
    }
    render(){
        const {caption}= this.props;
        const buttonStyle={
            border:'1px solid #ccc',
            marginRight:'5px',
            padding:'0 10px'
        };
        return (
            <div className="e-mb10">
                <button style={buttonStyle} onClick={this.onIncrement}>+</button>
                <button style={buttonStyle} onClick={this.onDecrement}>-</button>
                <span className="e-ml20">{caption} count:<em className="e-ml10">{this.state.count}</em></span>
            </div>
        )
    }
}
Couter.propTypes ={
    caption:PropTypes.string.isRequired,
    initValue:PropTypes.number,
    onUpdate:PropTypes.func
}